package com.ideal.frame.sys.service;

import com.ideal.frame.jpa.DSLRequest;
import com.ideal.frame.jpa.JpaRepositoryImpl;
import com.ideal.frame.sys.entity.QSysAddress;
import com.ideal.frame.sys.entity.SysAddress;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class SysAddressService {
    @PersistenceContext
    protected EntityManager entityManager;
    private JpaRepositoryImpl<SysAddress, Long> sysAddressLongJpaRepository;

    QSysAddress qSysAddress = QSysAddress.sysAddress;

    @PostConstruct
    public void initRepo() {
        sysAddressLongJpaRepository = new JpaRepositoryImpl<>(SysAddress.class, entityManager);
    }

    public List<SysAddress> listSysAddress(Long id) {
        DSLRequest request = new DSLRequest();
        request.addWhere(qSysAddress.parentId.eq(id));
        request.addWhere(qSysAddress.delFlag.isFalse());
        List<SysAddress> list = sysAddressLongJpaRepository.findAll(request);
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveAll(List<SysAddress> list) {
        sysAddressLongJpaRepository.saveAll(list);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateParentId() {
        List<SysAddress> all = sysAddressLongJpaRepository.findAll(qSysAddress.code.like("%0000"));
        List<SysAddress> up = new ArrayList<>();
        for (SysAddress province : all) {
            province.setParentId(0L);
            up.add(province);
            int code = Integer.parseInt(province.getCode().substring(0, 4));
            for (int i = 0; i < 100; i++) {
                code = code + 1;
                Optional<SysAddress> one = sysAddressLongJpaRepository.findOne(qSysAddress.code.eq(code + "00"));
                if (one.isPresent()) {
                    SysAddress city = one.get();
                    city.setParentId(province.getId());
                    up.add(city);

                    List<SysAddress> all1 = sysAddressLongJpaRepository.findAll(qSysAddress.code.like(code + "%")
                            .and(qSysAddress.code.ne(code + "00")));
                    for (SysAddress country : all1) {
                        country.setParentId(city.getId());
                        up.add(country);
                    }
                }
            }
        }
        System.out.println("*************" + up.size());
        System.out.println(up);
        sysAddressLongJpaRepository.saveAll(up);
    }
}